package com.xinfu.newproject.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.xinfu.newproject.R;
import com.xinfu.newproject.base.BaseActivity;
import com.xinfu.newproject.bean.login.LoginBean;
import com.xinfu.newproject.bean.pay.bean.PayRecordHeadBean;
import com.xinfu.newproject.contants.Constant;
import com.xinfu.newproject.interface_.SwichFragmentInterface;
import com.xinfu.newproject.presenter.PayCostPresenter;
import com.xinfu.newproject.ui.pay_cost.PayCostDetailActivity;
import com.xinfu.newproject.ui.pay_detail.BillingDetailsFragment;
import com.xinfu.newproject.adapter.park_adapter.PaymentRecordsAdapter;
import com.xinfu.newproject.util.BToast;
import com.xinfu.newproject.util.LogUtil;
import com.xinfu.newproject.util.NoticeEvent;
import com.xinfu.newproject.util.SPUtils;
import com.xinfu.newproject.util.rxHttp.HttpUtils;
import com.xinfu.newproject.view.IView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.xinfu.newproject.contants.Constant.LOGIN;
import static com.xinfu.newproject.contants.Constant.TENANTID;

public class PaymentRecordsActivity extends BaseActivity implements SwichFragmentInterface, IView.IPayRecordsView {

    @BindView(R.id.activity_payment_records_rv)
    RecyclerView mRecyclerView;

    private PaymentRecordsAdapter paymentRecordsAdapter;
    private List<PayRecordHeadBean> paymentRecordsBeanList;

    private FragmentManager fragmentManager;
    public final static int FRAGMENT_ZERO = 0;
    public final static int FRAGMENT_ONE = 1;

    private BillingDetailsFragment billingDetailsFragment;

    private PayCostPresenter payCostPresenter = new PayCostPresenter(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment_records);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        registerBack();
        setActivityTitle("缴费记录");
        initViewBind();
        initLisener();
    }

    private void initLisener() {
        if (isLogin()) {
//            payCostPresenter.payRecords();
            Map<String, String> map = new HashMap<>();
            map.put("userId", userId);
            Log.i("testPayCost", new Gson().toJson(map));
            HttpUtils.doPostT(Constant.baseUrl3 + "charge/charge/app/getUserPayRecords", token, map, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.i("testpayRecordsBean", e.getMessage());

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    EventBus.getDefault().post(new NoticeEvent("records", response.body().string()));
                }
            });
        }
    }


    private void initViewBind() {
        fragmentManager = getSupportFragmentManager();
//        paymentRecordsBeanList = getSampleData();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    }

    public void showFragment(int index, int type) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        hideFragments(ft);
        //注意这里设置位置
//        position = index;
        switch (index) {
            case FRAGMENT_ZERO:

                break;
            case FRAGMENT_ONE:
                /**
                 * 如果Fragment为空，就新建一个实例
                 * 如果不为空，就将它从栈中显示出来
                 */
//                if (billingDetailsFragment == null) {
//                    billingDetailsFragment = new BillingDetailsFragment();
//                    ft.add(R.id.activity_payment_records_fl, billingDetailsFragment);
//
//                } else {
//                    ft.show(billingDetailsFragment);
//                }
                break;
        }
        ft.commitAllowingStateLoss();
    }


    /**
     * 隐藏fragment
     *
     * @param transaction
     */
    private void hideFragments(FragmentTransaction transaction) {
//
//        if (billingDetailsFragment != null) {
//            transaction.hide(billingDetailsFragment);
//        }

    }

    @Override
    public void setSelectedFragment(int fragment, int type) {
        showFragment(fragment, type);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event) {
        if (event.getCls().equals("records")) {
            LogUtil.loge("testpayRecordsBean", event.getData().toString());
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(event.getData().toString());
                JSONObject jsonObject1 = jsonObject.getJSONObject("result");
                JSONObject object = new JSONObject(event.getData().toString());
                JSONObject object1 = object.getJSONObject("result");
                Map<String, Object> map = new Gson().fromJson(jsonObject1.toString(), new TypeToken<HashMap<String, Object>>() {
                }.getType());
                Set set = map.entrySet();
                Iterator it = set.iterator();
                List<String> list = new ArrayList<>();
                while (it.hasNext()) {
                    Map.Entry me = (Map.Entry) it.next();
                    list.add(me.getKey().toString());
                }
                paymentRecordsBeanList = getSampleData(list, object1);
                paymentRecordsAdapter = new PaymentRecordsAdapter(R.layout.item_payment_records_content, R.layout.item_payment_records_head, paymentRecordsBeanList);

                paymentRecordsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        JSONObject paymentRecordsBean = paymentRecordsBeanList.get(position).t;
                        Bundle bundle = new Bundle();
                        bundle.putString("response", new GsonBuilder()
                                .serializeNulls()
                                .create().toJson(paymentRecordsBean));
                        startIntentActivity(PayCostDetailActivity.class, bundle);
                    }
                });

                mRecyclerView.setAdapter(paymentRecordsAdapter);
//                paymentRecordsAdapter.setNewData(getSampleData(list,object1));
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 判断是否可以请求数据
     */
    String token, userId, userName, tenantId;

    private boolean isLogin() {

        LoginBean.ResultBean resultBean;
        String responseIntent = (String) SPUtils.get(this, LOGIN, "0");
        if (!responseIntent.equals("0")) {
            resultBean = new Gson().fromJson(responseIntent, LoginBean.ResultBean.class);
            token = resultBean.getToken();
            userId = resultBean.getUserInfo().getId();
            userName = resultBean.getUserInfo().getUsername();
            tenantId = (String) SPUtils.get(this, TENANTID, "0");
            if (tenantId.equals("0")) {
                BToast.showText(this, "请先绑定选择小区");
                return false;
            }
        } else {
            BToast.showText(this, "请先登录");
            return false;
        }

        return true;
    }

    @Override
    public String header() {
        return tenantId;
    }

    @Override
    public String userId() {
        return userId;
    }

    @Override
    public void showToast(String content) {
        BToast.showText(this, content);
    }

    @Override
    public void closeDispose(Disposable disposable) {

    }

    @Override
    public void showProgress() {
        showLoding();
    }

    @Override
    public void hideProgress() {
        hideLoding();
    }

    @Override
    public void getMsg(String payRecordsBean) {


    }

    public static List<PayRecordHeadBean> getSampleData(List<String> map, JSONObject object) {
        List<PayRecordHeadBean> list = new ArrayList<>();
        for (int i = 0; i < map.size(); i++) {
            PayRecordHeadBean residentBean = new PayRecordHeadBean(true, map.get(i), true);
            list.add(residentBean);
            JSONArray array = null;
            try {
                array = object.getJSONArray(map.get(i));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for (int j = 0; j < array.length(); j++) {
                JSONObject jsonObject2 = null;
                try {
                    jsonObject2 = array.getJSONObject(j);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
//                String ress = jsonObject2.getString("request");
//                LogUtil.loge("testOne",ress);
                list.add(new PayRecordHeadBean(jsonObject2));
            }

        }

        return list;
    }


}
